package com.mrjoew.weekend.web.securityapi;

import com.google.common.net.HttpHeaders;
import com.mrjoew.utils.IPUtil;
import com.mrjoew.utils.RequestUtil;
import com.mrjoew.weekend.web.BaseController;
import com.mrjoew.weekend.entities.ValidException;
import com.mrjoew.weekend.entities.dto.ContentSecurityDTO;
import com.mrjoew.weekend.entities.po.ContentSecurityPO;
import com.mrjoew.weekend.services.bz.ContentSecurityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 秘密的API
 */
@Api(tags = "秘密")
@ApiIgnore
@RequestMapping(value = "/csapi")
@RestController
public class ContentSecurityApiController extends BaseController {

    @Autowired
    private ContentSecurityService contentSecurityService;

    /**
     * 说的秘密
     *
     * @param input 内容
     * @return
     */
    @ApiOperation(value = "说秘密", notes = "发布秘密")
    @PostMapping(value = "/say")
    public void say(@Validated @RequestBody ContentSecurityDTO input, BindingResult bindingResult) throws ValidException {
        if (bindingResult.getErrorCount() > 0) {
            throw new ValidException(super.translateI18N(bindingResult));
        }

        try {
            ContentSecurityPO po = new ModelMapper().map(input, ContentSecurityPO.class);
            // 发送地址的IP
            po.setIpAddress(IPUtil.ipToLong(RequestUtil.getIpAddress(super.request)));
            // 发送方的客户端信息
            po.setRequestSourceInfo(super.request.getHeader(HttpHeaders.USER_AGENT));

            contentSecurityService.say(po);
        } catch (Exception e) {
            throw new ValidException();
        }
    }

    @ApiOperation(value = "获取秘密", notes = "全部秘密")
    @GetMapping(value = "/all")
    public Page<ContentSecurityPO> all(Pageable pageable) throws ValidException {
        try {
            return contentSecurityService.all(pageable);
        } catch (Exception e) {
            throw new ValidException("秘密获取失败");
        }
    }
}
